/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package src.view.security;


import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.FacesException;
import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.application.NavigationHandler;
import javax.faces.application.ViewHandler;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;
import src.domain.security.Users;
import src.services.security.UsersModel;
import src.util.Utils;

/**
 *
 * @author Yusup Jauhari Shandi <in.visi>
 */

@ManagedBean
@SessionScoped

public class LoginBean implements PhaseListener{
    private static final String homepage = "security/login.xhtml";
    /**
     * <p>The key for the session scoped attribute holding the
     * appropriate <code>Wuser</code> instance.</p>
     */
    public static final String USER_SESSION_KEY = "user";
    
    UsersModel userModel = new UsersModel();
    
    private String username;
    private String password;
    private boolean isLogin=false;
    private Users selectedUser;
    private String ipAddress;
    private String macAddress;
    

    public LoginBean() {
    }
    
    
    public String getUsername()
    {
        return username;
    }
    public void setUsername(String username)
    {
        this.username = username;
    }
    public String getPassword()
    {
        return password;
    }
    public void setPassword(String password)
    {
        this.password = password;
    }

    public boolean isIsLogin() {
        return isLogin;
    }

    public void setIsLogin(boolean isLogin) {
        this.isLogin = isLogin;
    }

    public String getIpAddress() {
        return ipAddress;
    }

    public void setIpAddress(String ipAddress) {
        this.ipAddress = ipAddress;
    }

    public String getMacAddress() {
        return macAddress;
    }
    

    public UsersModel getUserModel() {
        return userModel;
    }

    public void setUserModel(UsersModel userModel) {
        this.userModel = userModel;
    }
    
    
    
    public Users getSelectedUser()
    {
        if(selectedUser == null){
            selectedUser = new Users();
        }
        return selectedUser;
    }
    
    public void setSelectedUser(Users selectedUser)
    {
        this.selectedUser = selectedUser;
    }
    
    public String logout() {
       FacesContext context = FacesContext.getCurrentInstance();
       ExternalContext externalContext = context.getExternalContext(); 
      //  externalContext.getSessionMap().remove("LoginBean");

        HttpSession session = (HttpSession) externalContext.getSession(false);
        //session.getAttribute("ipAdress");
        /*session.removeAttribute("username");
        session.removeAttribute("userid");
        session.removeAttribute("fullname");
        * 
        */
        if (session != null)
            session.invalidate(); 
       isLogin = false;
       
      //   NavigationHandler nh = context.getApplication().getNavigationHandler();
         //   nh.handleNavigation(context, null, "logout");
        return "login";
         
    }
    public String login()
    {
         Map<String, String> filters = new HashMap<>();
        isLogin = false;
        filters.put("USER_NAME", this.username);
       
        byte[] defaultBytes = password.getBytes();
        try {
            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(defaultBytes);
            byte messageDigest[] = algorithm.digest();

            StringBuffer hexString = new StringBuffer();
            for (int i=0;i<messageDigest.length;i++) {
                    hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
            }            
            password=hexString+"";
            filters.put("PASSWORD", this.password);
            UsersModel helper = new UsersModel();      
            this.selectedUser = helper.login(filters);
            isLogin = true;
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(LoginBean.class.getName()).log(Level.SEVERE, null, ex);
        }
       //if("test".equalsIgnoreCase(getUsername()) && "test".equals(getPassword()))
      if (this.selectedUser!=null){
            FacesContext context = FacesContext.getCurrentInstance();
            ExternalContext ext = context.getExternalContext();
            HttpSession session = (HttpSession) ext.getSession(true);
            session.setAttribute("username", this.selectedUser.getUserName());
            session.setAttribute("userid", this.selectedUser.getUserId());
            session.setAttribute("fullname", this.selectedUser.getFullName());      
            session.setAttribute("groupid", this.selectedUser.getUgroup().getUgroupId());      
            
            HttpServletRequest request = (HttpServletRequest)ext.getRequest();
            ipAddress = src.util.Utils.getClientIpAddr(request);
            session.setAttribute("ipAddress", ipAddress);      
            //macAddress = src.util.Utils.getMacAddress(ipAddress);
            context.getExternalContext().getSessionMap().put(USER_SESSION_KEY, this.selectedUser);
            return "home";
        }
        else
        {
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage("alertMessage", new FacesMessage("Invalid UserName and Password"));
            return "login";
        }
    }
    
    
    
    public String updateUser()
    {
       // usersService.update(this.selectedUser);
        return "home";
    }
    
    public void onUserSelect(SelectEvent event)
    {        
    }
    public void onUserUnselect(UnselectEvent event)
    {
    }

    @Override
    public void afterPhase(PhaseEvent event) {
      //  throw new UnsupportedOperationException("Not supported yet.");
     
        //check have correct access
       
        //can't use this here. only valid at render response phase?
        FacesContext fc = event.getFacesContext();
        ExternalContext x = fc.getExternalContext();
        

    }

    @Override
    public void beforePhase(PhaseEvent event) {
        
       // throw new UnsupportedOperationException("Not supported yet.");
       /*  FacesContext fc = event.getFacesContext();

        // Check to see if they are on the login page.
        boolean loginPage =
	  fc.getViewRoot().getViewId().lastIndexOf("login") > -1 ? true : false;
        if (!loginPage && !isLogin) {
            NavigationHandler nh = fc.getApplication().getNavigationHandler();
            nh.handleNavigation(fc, null, "logout");
        }
        * 
        */
        
         FacesContext context = event.getFacesContext();
        ExternalContext ext = context.getExternalContext();
        HttpSession session = (HttpSession) ext.getSession(false);
        boolean newSession = (session == null) || (session.isNew());
        boolean postback = !ext.getRequestParameterMap().isEmpty();
        boolean timedout = postback && newSession;
       // if (timedout) {
        if (newSession){
            Application app = context.getApplication();
            ViewHandler viewHandler = app.getViewHandler();
            UIViewRoot view = viewHandler.createView(context, "/" + homepage);
            context.setViewRoot(view);
            context.renderResponse();
            try {
                viewHandler.renderView(context, view);
                context.responseComplete();
            } catch (Throwable t) {
                throw new FacesException("Session timed out", t);
            }
        } else {
         
                // context.getApplication().getNavigationHandler().handleNavigation(context, null, "logout");
                 //  ext.redirect("./security/login.xhtml");
                 NavigationHandler nh = context.getApplication().getNavigationHandler();
                 nh.handleNavigation(context, "home.xhtml", "logout");
                //context.getViewRoot().setViewId("/faces/security/login.xhtml");
         
        }
            
        
    }

    @Override
    public PhaseId getPhaseId() {
       // throw new UnsupportedOperationException("Not supported yet.");
         return PhaseId.RESTORE_VIEW;
    }
  
}
